﻿// ***********************************************************************
// Assembly         : Admin.Framework.Core.WebApi
// Author           : xwltz
// Created          : 2019-05-29
//
// Last Modified By : xwltz
// Last Modified On : 2019-05-29
// ***********************************************************************
// <summary>
//  配置入口
// </summary>
// ***********************************************************************

using System.IO;
using Admin.Framework.Core.Application;
using Autofac;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NSwag;

namespace Admin.Framework.Core.WebApi
{
    /// <summary>
    /// 配置入口
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 配置入口
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            #region 加载Log4Net配置并启用

            ILoggerRepository loggerRepository = LogManager.CreateRepository("LOG4NETCoreRepository");
            XmlConfigurator.Configure(loggerRepository, new FileInfo("Config/log4net.config"));

            #endregion
        }

        /// <summary>
        /// 全局配置对象
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddMvc();

            services.AddMemoryCache();

            #region 使用Cookie-Based认证

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.LoginPath = "Account/Login";
            });

            #endregion

            #region 添加跨域支持

            //todo:测试可以允许任意跨域，正式环境要加权限
            services.AddCors(options =>
            {
                options.AddPolicy("AllowCors", builder =>
                {
                    builder.WithOrigins("https://localhost:44358").AllowAnyHeader().AllowAnyMethod();
                });
            });
            
            #endregion

            #region 添加OpenAPI支持

            //services.AddSwaggerGen(options =>
            //{
            //    options.SwaggerDoc("v1", new Info
            //    {
            //        Version = "v1",
            //        Title = "Admin.Framework.Core.WebApi",
            //        Description = "A simple example ASP.NET Core Web API",
            //        TermsOfService = "None",
            //        Contact = new Contact
            //        {
            //            Name = "xwltz",
            //            Email = "61488281@qq.com",
            //            Url = "http://xwltz.github.com"
            //        }
            //    });
            //    options.DocumentFilter();
            //});

            services.AddSwaggerDocument(options =>
            {
                options.PostProcess = document =>
                {
                    document.Info.Version = "v1";
                    document.Info.Title = "Admin.Framework.Core.WebApi";
                    document.Info.Description = "A simple example ASP.NET Core Web API";
                    document.Info.TermsOfService = "None";
                    document.Info.Contact = new OpenApiContact
                    {
                        Name = "xwltz",
                        Email = "61488281@qq.com",
                        Url = "http://xwltz.github.com"
                    };
                    document.Info.License = new OpenApiLicense
                    {
                        Name = "MIT",
                        Url = "https://opensource.org/licenses/MIT"
                    };
                };
            });

            #endregion
        }

        /// <summary>
        /// Autofac
        /// </summary>
        /// <param name="builder"></param>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            // Add any Autofac modules or registrations.
            // This is called AFTER ConfigureServices so things you
            // register here OVERRIDE things registered in ConfigureServices.
            //
            // You must have the call to `UseServiceProviderFactory(new AutofacServiceProviderFactory())`
            // when building the host or this won't be called.
            builder.RegisterModule(new AutofacModule());
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // 如果是开发模式，显示详细报错信息
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

            // cors
            app.UseCors("AllowCors");

            // 可以访问根目录下面的静态文件
            app.UseStaticFiles();

            // 使用https
            app.UseHttpsRedirection();

            // 路由
            app.UseRouting();

            // 认证
            app.UseAuthorization();

            // 终结点
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

            #region 使用OpenAPI

            //启用中间件服务生成Swagger作为JSON终结点
            //app.UseSwagger();
            //启用中间件服务对swagger-ui，指定Swagger JSON终结点
            //app.UseSwaggerUI(c =>
            //{
            //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            //    c.DocExpansion(DocExpansion.None);
            //});

            app.UseOpenApi();
            app.UseReDoc();

#pragma warning disable 618
            //app.UseSwaggerUi();
#pragma warning restore 618

            //app.UseSwaggerUi3();

            #endregion
        }
    }
}